//
//  CommonTool.m
//  TooToo
//
//  Created by yjyan on 13-1-8.
//  Copyright (c) 2013年 appfactory. All rights reserved.
//

#import "CommonTool.h"
#import <QuartzCore/QuartzCore.h>
#import "FormatChecker.h"
#import "WXApi.h"

@implementation CommonTool

+(BOOL)canShowShareTool
{
    if ([WXApi isWXAppInstalled]) {
        return YES;
    }
    
    return NO;
}

+(void)clearCookie
{
    NSHTTPCookieStorage* cookies = [NSHTTPCookieStorage sharedHTTPCookieStorage];
    NSArray* tootooCookies = [cookies cookiesForURL:
                              [NSURL URLWithString:ServerDomain_Url]];
    NSLog(@"cookies = %@",tootooCookies);
    for (NSHTTPCookie* cookie in tootooCookies)
    {
        NSLog(@"cookie.name%@",cookie.name);

        [cookies deleteCookie:cookie];
    }
}

+(NSString *)replaceBr:(NSString *)str
{
    NSString *temp = str;
    NSRange range;
    while (range.length>0) {
        range = [temp rangeOfString:@"<br>"];
        if (range.length>0) {
            temp = [NSString stringWithFormat:@"%@\n%@",[temp substringToIndex:range.location],[temp substringFromIndex:range.location+4]];
            
        }
    }
    
    return temp;
}

+ (NSString *)getTrimText:(NSString *)string
{
    string = SafeString(string);
    
    string = [string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];

    if(string.length == 0)
        string = @"";
    return string;
}

//获取微信的access_token和openid
+(NSDictionary *)getAccess_token:(NSString *)code
{
    
    NSDictionary *dict;
    
    NSString *url =[NSString stringWithFormat:@"https://api.weixin.qq.com/sns/oauth2/access_token?appid=%@&secret=%@&code=%@&grant_type=authorization_code",@"wxdac37cee9ee2c117",@"64a850d99fa73b994b51d5b8462f776f",code];
    
    NSURL *zoneUrl = [NSURL URLWithString:url];
    
    NSString *zoneStr = [NSString stringWithContentsOfURL:zoneUrl encoding:NSUTF8StringEncoding error:nil];
    
    NSData *data = [zoneStr dataUsingEncoding:NSUTF8StringEncoding];
    
    if (data)
    {
        dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
    }
    return dict;
}

//根据access_token获取用户信息
+(NSDictionary *)getUserInfo:(NSString * )token
{
    NSDictionary *dic;
    
    NSString *url =[NSString stringWithFormat:@"https://api.weixin.qq.com/sns/userinfo?access_token=%@&openid=%@",token,@"wxdc51d52ff472c993"];
    
    NSURL *zoneUrl = [NSURL URLWithString:url];
    NSString *zoneStr = [NSString stringWithContentsOfURL:zoneUrl encoding:NSUTF8StringEncoding error:nil];
    NSData *data = [zoneStr dataUsingEncoding:NSUTF8StringEncoding];
    
    if (data)
    {
        dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
    }
    
    return dic;
}

//屏幕尺寸判断
+(KIDScreenSizeType)ScreenSizeType
{
    static KIDScreenSizeType screenSizeType = KIDScreenSizeiPhone5;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        if (IPHONEWIDTH >= 400.0) {
            screenSizeType = KIDScreenSizeiPhone6P;
        } else if (IPHONEWIDTH >= 360.0) {
            screenSizeType = KIDScreenSizeiPhone6;
        } else if (IPHONEHEIGHT <= 500.0) {
            screenSizeType = KIDScreenSizeiPhone4;
        }
    });
    return screenSizeType;
}


+(NSString *)getTimestamp
{
    //获得系统时间
    NSDate * senddate=[NSDate date];
    NSDateFormatter *dateformatter=[[NSDateFormatter alloc] init];
    [dateformatter setDateFormat:@"YYYY/MM/dd HH:mm:ss"];
    NSString * locationString=[dateformatter stringFromDate:senddate];
    
    return locationString;
}

+(NSString *)changeDate:(NSDate *)date toFormat:(NSString *)formatStr
{
    NSDateFormatter *dateformatter=[[NSDateFormatter alloc] init];
    [dateformatter setDateFormat:formatStr];
    NSString * locationString=[dateformatter stringFromDate:date];
    return locationString;
}

+(NSDate *)changeString:(NSString *)string toFormat:(NSString *)formatStr
{
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init] ;
    [formatter setDateFormat:formatStr];
    NSDate *date=[formatter dateFromString:string];
    return date;
}

//生成二维码 by 简书 http://www.jianshu.com/p/39dd77f359bd

+(UIImage *)encodeQRImageWithContent:(NSString *)content size:(CGSize)size {

    UIImage *codeImage = nil;
    
    NSData *stringData = [content dataUsingEncoding: NSUTF8StringEncoding];
    
    //生成
    CIFilter *qrFilter = [CIFilter filterWithName:@"CIQRCodeGenerator"];
    [qrFilter setValue:stringData forKey:@"inputMessage"];
    [qrFilter setValue:@"M" forKey:@"inputCorrectionLevel"];
    
    UIColor *onColor = [UIColor blackColor];
    UIColor *offColor = [UIColor whiteColor];
    
    //上色
    CIFilter *colorFilter = [CIFilter filterWithName:@"CIFalseColor"
                                       keysAndValues:
                             @"inputImage",qrFilter.outputImage,
                             @"inputColor0",[CIColor colorWithCGColor:onColor.CGColor],
                             @"inputColor1",[CIColor colorWithCGColor:offColor.CGColor],
                             nil];
    
    CIImage *qrImage = colorFilter.outputImage;
    CGImageRef cgImage = [[CIContext contextWithOptions:nil] createCGImage:qrImage fromRect:qrImage.extent];
    UIGraphicsBeginImageContext(size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetInterpolationQuality(context, kCGInterpolationNone);
    CGContextScaleCTM(context, 1.0, -1.0);
    CGContextDrawImage(context, CGContextGetClipBoundingBox(context), cgImage);
    codeImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    CGImageRelease(cgImage);
    
    return codeImage;
}

+(UIImage *)getImageByView:(UIView *)view
{
    UIImage *image = nil;

    CGSize size = CGSizeMake(view.frame.size.width, view.frame.size.height);
    
    UIGraphicsBeginImageContextWithOptions(size, NO, 3.0);
    [view.layer renderInContext:UIGraphicsGetCurrentContext()];
    [view drawViewHierarchyInRect:view.bounds afterScreenUpdates:YES];
    image = UIGraphicsGetImageFromCurrentImageContext();
    
    UIGraphicsEndImageContext();
    
    return image;
}

+(NSString *)getImageUrl:(NSString *)imgUrl size:(NSString *)size
{
    imgUrl = SafeString(imgUrl);
    
    NSRange range = [imgUrl rangeOfString:@"." options:NSBackwardsSearch];
    if (range.length >0) {
        imgUrl = [NSString stringWithFormat:@"%@_%@x%@%@",
                  [imgUrl substringToIndex:range.location],size,size,
                  [imgUrl substringFromIndex:range.location]];
    }
    
    return imgUrl;
}

+ (BOOL)findKeyboard
{
    UIView *keyboardView = nil;
    NSArray *windows = [[UIApplication sharedApplication] windows];
    for (UIWindow *window in [windows reverseObjectEnumerator])//逆序效率更高，因为键盘总在上方
    {
        keyboardView = [self findKeyboardInView:window];
        if (keyboardView)
        {
            return YES;
        }
    }
    return NO;
}
+ (UIView *)findKeyboardInView:(UIView *)view
{
    for (UIView *subView in [view subviews])
    {
        if (strstr(object_getClassName(subView), "UIKeyboard"))
        {
            return subView;
        }
        else
        {
            UIView *tempView = [self findKeyboardInView:subView];
            if (tempView)
            {
                return tempView;
            }
        }
    }
    return nil;
}

@end
